package com.example.xiefeihong.chatroom.activity;

import android.Manifest;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.example.xiefeihong.chatroom.R;
import com.example.xiefeihong.chatroom.dto.ChatMsg;
import com.example.xiefeihong.chatroom.dto.Status;
import com.example.xiefeihong.chatroom.dto.User;
import com.example.xiefeihong.chatroom.enums.AppEnum;
import com.example.xiefeihong.chatroom.enums.StatusCodeEnum;
import com.example.xiefeihong.chatroom.ui.Msg;
import com.example.xiefeihong.chatroom.ui.MsgAdapter;
import com.example.xiefeihong.chatroom.utils.DatabaseHelper;
import com.example.xiefeihong.chatroom.utils.HttpUtils;

import java.util.ArrayList;
import java.util.List;

import static com.example.xiefeihong.chatroom.utils.GsonUtils.gson;

/**
 * Created by xiefeihong on 17-10-11.
 */

public class RoomActivity extends BaseActivity {

    private ListView listChat;
    private EditText editMsg;
    private Button btnSend;
    private User user;
    private MsgAdapter adapter;
    private List<Msg> msgList = new ArrayList<>();
    private SQLiteDatabase db ;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message message) {
            switch (message.what) {
                case AppEnum.SHOW_RESPONSE:
                    Msg msg = (Msg) message.obj;
                    ChatMsg chatMsg = msg.getChatMsg();
                    ContentValues values = new ContentValues();
                    values.put("msg", chatMsg.getMsg());
                    values.put("form_user", chatMsg.getFormUser().getName());
                    db.insert("msg", null, values);
                    msgList.add(msg);
                    adapter.notifyDataSetChanged();
                    listChat.setSelection(msgList.size());
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.room_activity);
        DatabaseHelper dbHelper = new DatabaseHelper(this, "chat_room.db", null, 1);
        db = dbHelper.getWritableDatabase();
        Intent intent = getIntent();
        user = (User) intent.getSerializableExtra("user");
        adapter = new MsgAdapter(RoomActivity.this, R.layout.msg_item, msgList);
        editMsg = findViewById(R.id.edit_msg);
        btnSend = findViewById(R.id.btn_send);
        listChat = findViewById(R.id.list_chat);
        listChat.setAdapter(adapter);
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String context = editMsg.getText().toString();
                if(!context.equals("")){
                    ChatMsg chatMsg = new ChatMsg(user, context);
                    if (chatMsg.getMsg().equals("位置")) {
                        if (ActivityCompat.checkSelfPermission(RoomActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                                && ActivityCompat.checkSelfPermission(RoomActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                            return;
                        }
                        Location location = locationManager.getLastKnownLocation(provider);
                        chatMsg.setMsg("latitude : " + location.getLatitude() + "\nlongitude : " + location.getLongitude());
                    }
                    sendMsg(chatMsg);
                    editMsg.setText("");
                } else {
                    Toast.makeText(RoomActivity.this, "invalid string",Toast.LENGTH_SHORT).show();
                }
            }
        });
        receiveMsg();
    }

    private void sendMsg(final ChatMsg chatMsg){
        final String msgJson = gson.toJson(chatMsg);
        new Thread(new Runnable() {
            @Override
            public void run() {
                String responseText = HttpUtils.post("jms/send", msgJson);
                Status status = gson.fromJson(responseText, Status.class);
                if(!status.getStatusCode().equals(StatusCodeEnum.NORMAL.toString())){
                    Toast.makeText(RoomActivity.this, "服务器开小差了 -_-!!", Toast.LENGTH_SHORT).show();
                }
            }
        }).start();
    }

    private void receiveMsg(){
        final ChatMsg chatMsg = new ChatMsg(user);
        final String msgJson = gson.toJson(chatMsg);
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    Log.d("RoomActivity", "waiting for response");
                    String responseText = HttpUtils.post("jms/receive", msgJson);
                    ChatMsg resChatMsg = gson.fromJson(responseText, ChatMsg.class);
                    Message message = new Message();
                    message.what = AppEnum.SHOW_RESPONSE;
                    String forUser = resChatMsg.getFormUser().getName();
                    if(forUser.equals(user.getName())){
                        message.obj =  new Msg(resChatMsg, Msg.TYPE_SENT);
                    } else {
                        message.obj =  new Msg(resChatMsg, Msg.TYPE_RECEIVED);
                    }
                    handler.sendMessage(message);
                }
            }
        }).start();
    }

}
